package com.testmanager.testmananger.shuiyou.strCompare.respository;


import com.querydsl.core.types.dsl.BooleanExpression;
import com.testmanager.testmananger.shuiyou.strCompare.domain.QSyDbManagerEntity;
import com.testmanager.testmananger.shuiyou.strCompare.domain.SyDbManagerEntity;
import com.testmanager.testmananger.shuiyou.strCompare.dto.DbManagerSearchDto;
import com.testmanager.testmananger.shuiyou.strCompare.service.SyProjectService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;


@Repository
@Transactional(readOnly = true)
@Slf4j
public class SyDbManagerCustom {

    @Autowired
    SyDbManagerRepository syDbManagerRepository;

    @Autowired
    SyProjectService syProjectService;


    public Page<SyDbManagerEntity> search(DbManagerSearchDto dbManagerSearchDto){
        log.info("SyDbManagerCustom:{}",dbManagerSearchDto);
        QSyDbManagerEntity qSyDbManagerEntity = QSyDbManagerEntity.syDbManagerEntity;
        BooleanExpression expression = qSyDbManagerEntity.id.isNotNull();
        if (dbManagerSearchDto.getDbName() != null && dbManagerSearchDto.getDbName() != "" &&!StringUtils.isEmpty(dbManagerSearchDto.getDbName())){
            expression = expression.and(qSyDbManagerEntity.dbname.like("%"+dbManagerSearchDto.getDbName().trim()+"%"));
        }
        if (dbManagerSearchDto.getUrl() != null && dbManagerSearchDto.getUrl() != "" && !StringUtils.isEmpty(dbManagerSearchDto.getUrl())){
           // log.info("likeurl:{}","%"+dbManagerSearchDto.getUrl().trim()+"%");
            expression = expression.and(qSyDbManagerEntity.url.like("%"+dbManagerSearchDto.getUrl().trim()+"%"));
        }
        if (dbManagerSearchDto.getProjectId() != 0){
//            expression = expression.and(qSyDbManagerEntity.projectId.eq(dbManagerSearchDto.getProjectId()));
            List<Long> list = syProjectService.findAllChildRenIds(dbManagerSearchDto.getProjectId());
            expression = expression.and(qSyDbManagerEntity.projectId.in(list));

        }
       // expression = expression.and(qSyDbManagerEntity)

        Sort orders = Sort.by(Sort.Order.desc(qSyDbManagerEntity.id.getMetadata().getName()),Sort.Order.asc(qSyDbManagerEntity.createdDate.getMetadata().getName()));
        Pageable pageable = PageRequest.of(dbManagerSearchDto.getPageNum()-1,dbManagerSearchDto.getPageSize(),orders);

        return syDbManagerRepository.findAll(expression,pageable);

    }
}
